<template>
  <el-form :model="user" ref="form" :rules="rules">
    <el-form-item label="原密码" prop="password">
      <el-input v-model.trim="user.password" show-password />
    </el-form-item>
    <el-form-item label="新密码" prop="newPassword">
      <el-input v-model.trim="user.newPassword" show-password/>
    </el-form-item>
    <el-form-item label="确认密码" prop="checkPassword">
      <el-input v-model.trim="user.checkPassword" show-password/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submit">提交</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
  export default {
    name: "Password",
    data(){
      // 密码验证逻辑
      let validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'));
        } else {
          if (this.user.checkPassword !== '') {
            this.$refs.form.validateField('checkPass');
          }
          callback();
        }
      };
      // 确认密码的验证逻辑
      let validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.user.newPassword) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
      return {
        rules: {
          password: [
            { validator: validatePass, trigger: 'blur' }
          ],
          newPassword:[
            { validator: validatePass, trigger: 'blur' }
          ],
          checkPassword: [
            { validator: validatePass2, trigger: 'blur' }
          ],
        },
        user:{
          password:"",
          newPassword:"",
          checkPassword:""
        }
      }
    },
    methods: {
      submit() {
        this.$refs.form.validate((valid) => {
          if (valid) {
            this.$api.user.updatePassword(this.user).then(
              res => {
                if(res.code === 200) {
                  this.$message({ message: '修改成功', type: 'success' });
                  this.$refs.form.resetFields();
                }else {
                  this.$message({message: `修改失败, ${res.msg}`, type: 'error'})
                }
              },
              () => {
                this.$message({message: '操作失败, 服务器异常', type: 'error'});
              });
          }else {
            return false;
          }
        });

      }
    }
  }
</script>
